package org.jeecg.modules.flower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.chvegetable.service.IFlowerTagBookService;
import org.jeecg.modules.chvegetable.service.IFlowerTagBookpreService;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.mapper.*;
import org.jeecg.modules.flower.service.IFlowerPreService;
import org.jeecg.modules.flower.service.IFlowerTagpreService;
import org.jeecg.modules.flower.service.XsglService;
import org.jeecg.modules.flower.util.CommonUtil;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 销售确认单主表
 * 根据预出库单的单号进行扣减和标识
 * @Author: jeecg-boot
 * @Date: 2022-06-27
 * @Version: V1.0
 */
@Service
public class FlowerPreServiceImpl extends ServiceImpl<FlowerPreMapper, FlowerPre> implements IFlowerPreService {

    @Autowired
    private FlowerPreMapper flowerPreMapper;
    @Autowired
    private FlowerPreinfoMapper flowerPreinfoMapper;
    @Autowired
    private FlowerPreinfoHsMapper flowerPreinfoHsMapper;
    @Autowired
    private IFlowerTagpreService flowerTagpreService;
    @Autowired
    private XsglService xsglService;
    @Autowired
    private IFlowerTagBookpreService flowerTagBookpreService;
    @Autowired
    private FlowerOutorderPreinfoMapper flowerOutorderPreinfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMain(FlowerPre flowerPre, List<FlowerPreinfo> flowerPreinfoList, List<FlowerPreinfoHs> flowerPreinfoHsList) throws IOException {
        //总数量是否等于预出库总数量
        isNumOk(flowerPre, flowerPreinfoList, flowerPreinfoHsList);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        //自动生成出库单号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateNo = simpleDateFormat.format(new Date());
        String refex = "CH-XSQR-" + dateNo;
        LambdaQueryWrapper<FlowerPre> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(FlowerPre::getNo, refex);
        lambdaQueryWrapper.orderByDesc(FlowerPre::getNo);
        List<FlowerPre> list = this.list(lambdaQueryWrapper);
        String oldNo = "";
        if (list.size() > 0) {
            oldNo = list.get(0).getNo();
        }
        String no1 = CommonUtil.getNo("CH-XSQR-", oldNo, 3);
        flowerPre.setNo(no1);//自动生成出库单号
        //自动生成出库单号========end====
        flowerPre.setState(0);
        flowerPre.setCreateUser(sysUser.getUsername());
        if (StringUtils.isBlank(flowerPre.getUser())) {
            flowerPre.setUser("零售");
        }

        //自动计算合计
        flowerPre = sumNumPrice(flowerPre, flowerPreinfoList, flowerPreinfoHsList);
//		Integer snum = 0;
//		BigDecimal sumTotalprice = new BigDecimal(0);
//		for (FlowerPreinfo flowerPreinfo : flowerPreinfoList) {
//			Integer snumber = flowerPreinfo.getNumber();
//			if (snumber == null) {
//				snumber = 0;
//			}
//			snum += snumber;
//			BigDecimal totalprice = flowerPreinfo.getTotalprice();
//			if (totalprice == null) {
//				totalprice = new BigDecimal(0);
//			}
//			sumTotalprice = sumTotalprice.add(totalprice);
//		}
//		flowerPre.setNumber(snum);
//		flowerPre.setToalprice(sumTotalprice.setScale(2, RoundingMode.HALF_UP));
//		Integer numberhs = 0;
//		BigDecimal sumTotalpricehs = new BigDecimal(0);
//		for (FlowerPreinfoHs flowerPreinfo : flowerPreinfoHsList) {
//			Integer snumber = flowerPreinfo.getNumber();
//			if (snumber == null) {
//				snumber = 0;
//			}
//			numberhs += snumber;
//			BigDecimal totalprice = flowerPreinfo.getTotalprice();
//			if (totalprice == null) {
//				totalprice = new BigDecimal(0);
//			}
//			sumTotalpricehs = sumTotalpricehs.add(totalprice);
//		}
//		flowerPre.setNumberhs(numberhs);
//		flowerPre.setToalpricehs(sumTotalpricehs.setScale(2, RoundingMode.HALF_UP));

        flowerPreMapper.insert(flowerPre);
        if (flowerPreinfoList != null && flowerPreinfoList.size() > 0) {
            for (FlowerPreinfo entity : flowerPreinfoList) {
                //外键设置
                entity.setOrderId(flowerPre.getId());
                flowerPreinfoMapper.insert(entity);
            }
        }
        //货损
        if (flowerPreinfoHsList != null && flowerPreinfoHsList.size() > 0) {
            for (FlowerPreinfoHs entity : flowerPreinfoHsList) {
                //外键设置
                entity.setOrderId(flowerPre.getId());
                flowerPreinfoHsMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMain(FlowerPre flowerPre, List<FlowerPreinfo> flowerPreinfoList, List<FlowerPreinfoHs> flowerPreinfoHsList) throws IOException {
        isNumOk(flowerPre, flowerPreinfoList, flowerPreinfoHsList);//总数量是否等于预出库总数量

        Integer state = flowerPre.getState();
        if (state != 0) {
            throw new RuntimeException("只有草稿状态的才能进行修改！");
        }
        flowerPre = sumNumPrice(flowerPre, flowerPreinfoList, flowerPreinfoHsList);
        flowerPreMapper.updateById(flowerPre);

        //1.先删除子表数据
        flowerPreinfoMapper.deleteByMainId(flowerPre.getId());
        flowerPreinfoHsMapper.deleteByMainId(flowerPre.getId());

        //2.子表数据重新插入
        if (flowerPreinfoList != null && flowerPreinfoList.size() > 0) {
            for (FlowerPreinfo entity : flowerPreinfoList) {
                //外键设置
                entity.setOrderId(flowerPre.getId());
                flowerPreinfoMapper.insert(entity);
            }
        }
        //货损
        if (flowerPreinfoHsList != null && flowerPreinfoHsList.size() > 0) {
            for (FlowerPreinfoHs entity : flowerPreinfoHsList) {
                //外键设置
                entity.setOrderId(flowerPre.getId());
                flowerPreinfoHsMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String id) throws IOException {
        //归还 锁定金额，传至销售系统
        FlowerPre flowerPreOld = this.getById(id);
        Integer state = flowerPreOld.getState();
        if (state != 0) {
            throw new RuntimeException("只有草稿状态的才能进行修改！");
        }
        flowerPreOld.setState(-2);
        flowerPreMapper.updateById(flowerPreOld);
//        flowerPreinfoMapper.deleteByMainId(id);
//        flowerPreinfoHsMapper.deleteByMainId(id);
//        flowerPreMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delBatchMain(Collection<? extends Serializable> idList) throws IOException {
        for (Serializable id : idList) {
            //归还 锁定金额，传至销售系统
            FlowerPre flowerPreOld = this.getById(id);
            Integer state = flowerPreOld.getState();
            if (state != 0) {
                throw new RuntimeException("只有草稿状态的才能进行修改！");
            }
            flowerPreOld.setState(-2);
            flowerPreMapper.updateById(flowerPreOld);

//            flowerPreinfoMapper.deleteByMainId(id.toString());
//            flowerPreinfoHsMapper.deleteByMainId(id.toString());
//            flowerPreMapper.deleteById(id);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finSureOut(FlowerPre flowerPreOld) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

        //1、修改预出库主表财务确认人
//            状态（0草稿，1基地负责人审批，2运管备案，3财务确认，）
        if (flowerPreOld != null && StringUtils.isNotBlank(flowerPreOld.getFinaSureUser())) {
            throw new RuntimeException("还不可以财务确认");
        }
        if (flowerPreOld.getState().compareTo(3) == 0) {
            throw new RuntimeException("财务已经确认过了");
        }
        if (flowerPreOld.getState().compareTo(2) != 0) {
            throw new RuntimeException("还不可以财务确认");
        }


        flowerPreOld.setSealSureUser(flowerPreOld.getSealSureUser());
        flowerPreOld.setSealSureTime(flowerPreOld.getSealSureTime());
        flowerPreOld.setPipSure(flowerPreOld.getPipSure());
        flowerPreOld.setPipSureTime(flowerPreOld.getPipSureTime());

        flowerPreOld.setFinaSureUser(sysUser.getRealname());
        flowerPreOld.setFinaSureTime(new Date());
        flowerPreOld.setState(3);
        this.updateById(flowerPreOld);

        //扣减预出库的台账库存
//		subTagPreInfo(flowerPreOld);
        flowerTagBookpreService.outPre(flowerPreOld.getId());
        if(flowerTagBookpreService.checkBooksIsErr()){
            throw  new RuntimeException("库存台账数据有误，请联系管理员！");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finSureOutBack(FlowerPre flowerPreOld) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        if (flowerPreOld == null || StringUtils.isBlank(flowerPreOld.getFinaSureUser())) {
            throw new RuntimeException("财务还未确认");
        }
        if (flowerPreOld.getState().compareTo(3) != 0) {
            throw new RuntimeException("不能再撤销确认");
        }
        if (!sysUser.getRealname().equals(flowerPreOld.getFinaSureUser())) {
            throw new RuntimeException("只能撤销自己确认的单据");
        }

        flowerTagBookpreService.outPreBack(flowerPreOld.getId());
        if(flowerTagBookpreService.checkBooksIsErr()){
            throw  new RuntimeException("库存台账数据有误，请联系管理员！");
        }

        //1、修改预出库主表财务确认人

        flowerPreOld.setSealSureUser(flowerPreOld.getSealSureUser());
        flowerPreOld.setSealSureTime(flowerPreOld.getSealSureTime());
        flowerPreOld.setPipSure(flowerPreOld.getPipSure());
        flowerPreOld.setPipSureTime(flowerPreOld.getPipSureTime());
        flowerPreOld.setFinaSureUser("");
        flowerPreOld.setFinaSureTime(null);
        flowerPreOld.setState(2);
        this.updateById(flowerPreOld);

        //扣减预出库的台账库存
//        subTagPreInfoBack(flowerPreOld);

    }


    private FlowerPre sumNumPrice(FlowerPre flowerPre, List<FlowerPreinfo> flowerPreinfoList, List<FlowerPreinfoHs> flowerPreinfoHsList) {
//自动计算合计
        BigDecimal snum = BigDecimal.ZERO;
        BigDecimal sumTotalprice = new BigDecimal(0);
        for (FlowerPreinfo flowerPreinfo : flowerPreinfoList) {
            BigDecimal snumber = flowerPreinfo.getNumber();
            if (snumber == null) {
                snumber = BigDecimal.ZERO;
            }
            snum =snum.add( snumber);
            BigDecimal totalprice = flowerPreinfo.getTotalprice();
            if (totalprice == null) {
                totalprice = new BigDecimal(0);
            }
            sumTotalprice = sumTotalprice.add(totalprice);
        }
        flowerPre.setNumber(snum);
        flowerPre.setToalprice(sumTotalprice.setScale(2, RoundingMode.HALF_UP));
        BigDecimal numberhs = BigDecimal.ZERO;
        BigDecimal sumTotalpricehs = new BigDecimal(0);
        for (FlowerPreinfoHs flowerPreinfo : flowerPreinfoHsList) {
            BigDecimal snumber = flowerPreinfo.getNumber();
            if (snumber == null) {
                snumber = BigDecimal.ZERO;
            }
            numberhs  =numberhs.add( snumber);
            BigDecimal totalprice = flowerPreinfo.getTotalprice();
            if (totalprice == null) {
                totalprice = new BigDecimal(0);
            }
            sumTotalpricehs = sumTotalpricehs.add(totalprice);
        }
        flowerPre.setNumberhs(numberhs);
        flowerPre.setToalpricehs(sumTotalpricehs.setScale(2, RoundingMode.HALF_UP));
        return flowerPre;
    }

    /**
     * @return void
     * @descriptionauthor 扣减预出库库存-- 根据预出库单号
     * @author gf
     * 2022-12-22 14:11
     * [id]
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void subTagPreInfo(FlowerPre flowerPre) {
        List<FlowerPreinfo> flowerPreinfoList = flowerPreinfoMapper.selectByMainId(flowerPre.getId());
        List<FlowerPreinfoHs> flowerPreinfoHsList = flowerPreinfoHsMapper.selectByMainId(flowerPre.getId());
        BigDecimal integer = BigDecimal.ZERO;
        //修改预出库预出库台账-----确认销售
        for (FlowerPreinfo flowerPreinfo : flowerPreinfoList) {
            String sourceBase = flowerPreinfo.getSourceBase();
            String sourceGreenhouse = flowerPreinfo.getSourceGreenhouse();
            String storehouse = flowerPreinfo.getStorehouse();
            String variety = flowerPreinfo.getVariety();
            String varietyCode = flowerPreinfo.getVarietyCode();
            String packingSpecifications = flowerPreinfo.getPackingSpecifications();
            String flowerPoleLength = flowerPreinfo.getFlowerPoleLength();
            BigDecimal number = flowerPreinfo.getNumber();
            if (number.compareTo(BigDecimal.ZERO) <= 0) {
                throw new RuntimeException(variety + "(" + varietyCode + ")确认数量为0，请重新填写数量");
            }
//            integer += flowerTagpreService.outTagpre(flowerPre.getOutorderPreNo(), flowerPreinfo.getId(), sourceBase, sourceGreenhouse, flowerPre.getChannel(), flowerPre.getAccountno(), variety, varietyCode, storehouse, packingSpecifications, flowerPoleLength, number, 2);
        }
        //修改预出库预出库台账-----货损
        for (FlowerPreinfoHs flowerPreinfo : flowerPreinfoHsList) {
            String sourceBase = flowerPreinfo.getSourceBase();
            String sourceGreenhouse = flowerPreinfo.getSourceGreenhouse();
            String storehouse = flowerPreinfo.getStorehouse();
            String variety = flowerPreinfo.getVariety();
            String varietyCode = flowerPreinfo.getVarietyCode();
            String packingSpecifications = flowerPreinfo.getPackingSpecifications();
            String flowerPoleLength = flowerPreinfo.getFlowerPoleLength();
            BigDecimal number = flowerPreinfo.getNumber();
            if (number.compareTo(BigDecimal.ZERO) <= 0) {
                throw new RuntimeException(variety + "(" + varietyCode + ")确认数量为0，请重新填写数量");
            }
//            integer += flowerTagpreService.outTagpre(flowerPre.getOutorderPreNo(), flowerPreinfo.getId(), sourceBase, sourceGreenhouse, flowerPre.getChannel(), flowerPre.getAccountno(), variety, varietyCode, storehouse, packingSpecifications, flowerPoleLength, number, 3);
        }
        if (integer.compareTo((flowerPre.getNumber().add (flowerPre.getNumberhs() ))) != 0) {
            throw new RuntimeException("销售确认总数(" + (flowerPre.getNumber() .add( flowerPre.getNumberhs()) )+ ")和预出库单(" + flowerPre.getOutorderPreNo() + ")" + integer + "总数不相等，请检查数量");
        }
    }

    /**
     * @return void
     * @descriptionauthor 扣减预出库库存-- 根据预出库单号 --撤销
     * @author gf
     * 2022-12-22 14:11
     * [id]
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void subTagPreInfoBack(FlowerPre flowerPre) {
        LambdaQueryWrapper<FlowerTagpre> tagpreQuery = new LambdaQueryWrapper<>();
        tagpreQuery.inSql(FlowerTagpre::getOutorderId, "  SELECT info.id FROM  t_flower_outorder_preinfo info,t_flower_outorder_pre main  " +
                "WHERE info.order_id = main.id and  main.order_no = '" + flowerPre.getOutorderPreNo() + "'");
        List<FlowerTagpre> flowerTagpres = flowerTagpreService.list(tagpreQuery);
        List<String> ids = new ArrayList<>();
        for (FlowerTagpre flowerTagpre : flowerTagpres) {
            ids.add(flowerTagpre.getId());
        }
        if (ids.size() > 0) {
            UpdateWrapper<FlowerTagpre> updateWrapper = new UpdateWrapper<>();
            updateWrapper.in("id", ids);
            updateWrapper.set("state", 1);
            updateWrapper.set("pre_sure_id", "");
            flowerTagpreService.update(updateWrapper);
        }
    }

    /**
     * @return
     * @descriptionauthor 判断预出库的总数量是否等于销售确认的总数量。金额不做判断。
     * @author gf
     * 2022-12-26 13:15
     */
    private void isNumOk(FlowerPre flowerPre, List<FlowerPreinfo> flowerPreinfoList, List<FlowerPreinfoHs> flowerPreinfoHsList) {
        String outorderPreNo = flowerPre.getOutorderPreNo();
        if (StringUtils.isBlank(outorderPreNo)) {
            throw new RuntimeException("预出库单号不能为空！");
        }
        List<FlowerOutorderPreinfo> flowerOutorderPreinfos = flowerOutorderPreinfoMapper.selectByMainNo(outorderPreNo);
        BigDecimal orderPreNumSum = BigDecimal.ZERO;
        for (FlowerOutorderPreinfo flowerOutorderPreinfo : flowerOutorderPreinfos) {
            orderPreNumSum = orderPreNumSum.add(flowerOutorderPreinfo.getNumber());
        }
        BigDecimal preNumSum = BigDecimal.ZERO;
        for (FlowerPreinfo flowerPreinfo : flowerPreinfoList) {
            preNumSum  = preNumSum.add(flowerPreinfo.getNumber());
        }
        BigDecimal preNumSumHS =BigDecimal.ZERO;
        for (FlowerPreinfoHs flowerPreinfoHs : flowerPreinfoHsList) {
            preNumSumHS = preNumSumHS.add(flowerPreinfoHs.getNumber());
        }
        if (orderPreNumSum.compareTo((preNumSum .add( preNumSumHS))) != 0) {
            throw new RuntimeException("预出库单号(" + outorderPreNo + ")总数量（" + orderPreNumSum + "）不等于本次确认的总数量" +preNumSum .add( preNumSumHS) + "（确认:" + preNumSum + "+ 货损:" + preNumSumHS + "）请检查数量！");
        }
    }
}
